import csv
import os
import tkinter as tk
from tkinter import filedialog, scrolledtext
from collections import defaultdict

def extract_array_names(bta_data):
    array_names = []
    for item in bta_data:
        # 寻找形如 "uint32_t BTA_06_04" 或 "uint32_t BTA_06_04_1" 的数组名
        start_idx = item.find("BTA_")
        if start_idx != -1:
            end_idx = item.find(" ", start_idx)
            if end_idx == -1:
                end_idx = len(item)
            array_names.append(item[start_idx:end_idx])
    return array_names

def generate_bta_processing_code(bta_data):
    output_code = ""
    if not bta_data:
        return output_code

    processed_switches = set()
    output_code += "static int mipi_bta_process(uint32_t data, uint32_t data_bak, uint32_t data_bak2)\n"
    output_code += "{\n"
    output_code += "  uint8_t data0 = 0, data1 = 0, data2 = 0, data3 = 0;\n"
    output_code += "  data0 = (data >> 0)  &  0xff;\n"
    output_code += "  data1 = (data >> 8)  &  0xff;\n"
    output_code += "  data2 = (data >> 16) &  0xff;\n"
    output_code += "  data3 = (data >> 24) &  0xff;\n"
    output_code += '  // printf("BT1:0x%x, T2:0x%x, T3:0x%x\\r\\n", data, data_bak, data_bak2);\n\n'
    output_code += "  switch(data0)\n"
    output_code += "  {\n"

    for item in bta_data:
        array_name_parts = item.split("_")
        if len(array_name_parts) < 3:
            continue
        switch_var = array_name_parts[1]
        case_var = array_name_parts[2]
        if switch_var not in processed_switches:
            output_code += f"    case 0x{switch_var}:\n"
            output_code += f"      // TODO: handle case {switch_var}\n"
            processed_switches.add(switch_var)
        output_code += f"      // case 0x{case_var}: handle {item}\n"

    if processed_switches:
        output_code += "    break;\n"

    output_code += "\n    default:\n"
    output_code += '        // printf("other bta: 0x%x\\n", data);\n'
    output_code += "        break;\n"
    output_code += "  }\n"
    output_code += "}\n"
    return output_code

def process_bta_data(bta_data):
    array_counts = defaultdict(int)
    unique_bta_data = []
    seen_arrays = defaultdict(set)
    for item in bta_data:
        array_name_start = item.find("BTA_")
        if array_name_start != -1:
            array_name = item[array_name_start:].split()[0]
            if array_name not in seen_arrays or item not in seen_arrays[array_name]:
                unique_bta_data.append(item)
                seen_arrays[array_name].add(item)
        else:
            unique_bta_data.append(item)
    return unique_bta_data

def read_csv_and_process_bta(output_textbox, file_paths):
    bta_data = []
    for file_path in file_paths:
        file_name = os.path.splitext(os.path.basename(file_path))[0]
        try:
            with open(file_path, encoding="utf-8") as csvfile:
                reader = csv.reader(csvfile)
                for row in reader:
                    # 假设BTA数据在每行的第一个字段
                    if row and "BTA_" in row[0]:
                        bta_data.append(row[0])
        except Exception as e:
            output_textbox.insert(tk.END, f"{file_name} 读取失败: {e}\n")
    array_names = extract_array_names(bta_data)
    bta_code = generate_bta_processing_code(array_names)
    code_window = tk.Toplevel()
    code_window.title("生成的bta代码")
    code_textbox = tk.Text(code_window, wrap=tk.WORD, height=30, width=100)
    code_textbox.insert(tk.END, bta_code)
    code_textbox.pack(fill=tk.BOTH, expand=True)

def select_files_and_process():
    file_paths = filedialog.askopenfilenames(
        title="选择一个或多个CSV文件",
        filetypes=[("CSV Files", "*.csv")]
    )
    if file_paths:
        root = tk.Tk()
        root.withdraw()
        output_window = tk.Toplevel(root)
        output_window.title("处理结果")
        output_textbox = scrolledtext.ScrolledText(output_window, wrap=tk.WORD, height=30, width=100)
        output_textbox.pack(fill=tk.BOTH, expand=True)
        read_csv_and_process_bta(output_textbox, file_paths)
        root.mainloop()

def handle_read_csv(output_textbox, file_path):
    output_textbox.delete('1.0', tk.END)
    try:
        with open(file_path, encoding="utf-8") as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                output_textbox.insert(tk.END, ",".join(row) + "\n")
    except FileNotFoundError:
        output_textbox.insert(tk.END, "文件未找到。\n")
    except Exception as e:
        output_textbox.insert(tk.END, f"发生错误: {e}\n")

def open_csv_file_and_process():
    file_paths = filedialog.askopenfilenames(
        title="选择一个或多个CSV文件",
        filetypes=[("CSV Files", "*.csv")]
    )
    if file_paths:
        root = tk.Tk()
        root.withdraw()
        output_window = tk.Toplevel(root)
        output_window.title("处理结果")
        output_textbox = scrolledtext.ScrolledText(output_window, wrap=tk.WORD, height=30, width=100)
        output_textbox.pack(fill=tk.BOTH, expand=True)